package com.dataimport.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataimport.entity.sourceentity.BookLendingHistory;
import com.dataimport.entity.targetentity.LibraryBorrowRecords;
import com.dataimport.mapper.BookLendingHistoryMapper;
import com.dataimport.mapper.LibraryBorrowRecordsMapper;
import com.dataimport.service.LibraryBorrowRecordsService;
import com.dataimport.utils.HasNullFieldUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * impl图书馆借记录服务
 *
 * @author 章珑赢
 * @date 2022/10/04
 */
@Service
public class LibraryBorrowRecordsServiceImpl extends ServiceImpl<LibraryBorrowRecordsMapper, LibraryBorrowRecords> implements LibraryBorrowRecordsService {
    @Autowired
    private BookLendingHistoryMapper bookLendingHistoryMapper;
    @Override
    public void dealWithLibraryBorrowRecords() {
        DynamicDataSourceContextHolder.push("mysql2");
        List<BookLendingHistory> bookLendingHistories = bookLendingHistoryMapper.selectList(null);
        if(CollectionUtils.isNotEmpty(bookLendingHistories)){
            List<LibraryBorrowRecords> libraryAccessRecords = bookLendingHistories.stream().parallel().map(bookLendingHistory-> {
                LibraryBorrowRecords libraryBorrowRecords=new LibraryBorrowRecords();
                libraryBorrowRecords.setUserId(Long.parseLong(bookLendingHistory.getDzh()));
                libraryBorrowRecords.setBorrowTime(DateUtil.parse(bookLendingHistory.getJcrq()));
                libraryBorrowRecords.setShouldReturnTime(DateUtil.parse(bookLendingHistory.getYhrq()));
                libraryBorrowRecords.setReturnTime(DateUtil.parse(bookLendingHistory.getGhsj()));
                return libraryBorrowRecords;
            }).collect(Collectors.toList());
            libraryAccessRecords.forEach(System.out::println);
            DynamicDataSourceContextHolder.poll();
            insertLibraryBorrowRecords(libraryAccessRecords);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    void insertLibraryBorrowRecords(List<LibraryBorrowRecords> libraryAccessRecords){
        DynamicDataSourceContextHolder.push("mysql1");
        this.saveBatch(libraryAccessRecords);
        DynamicDataSourceContextHolder.poll();
    }

}

